/*
paket - a simple AUR searcher
copyright (C) 2021 noStress

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include "paket_parse.h"

void
usage()
{
	printf("usage:  paket <operation> [...]\n");
	printf("operations\n");
	printf("	paket -h --help}\n");
	printf("	paket -s --search [package(s)]\n");
	printf("	paket -e --exact [package(s)]\n");
	printf("	paket -V --version}\n");
	exit(0);
}

void
errorAndDie(int ec)
{
	if (ec == 1)
		printf("error: conflicting options\n");
	else if (ec == 2)
		printf("error: must have at least one option\n");
	else if (ec == 3) {
		printf("error: cannot search without a package\n");
		usage(1);
	}
	else {
		printf("something went wrong, given code %d\n", ec);
		printf("tell the guy who makes this to update the basic checking");
	}
	exit(1);
}

void
version()
{
	printf("\n");
	printf("\033[1;36m  ████   \033[1;33mPaket\n");
	printf("\033[1;36m  █  █   Version 1.0\n");
	printf("\033[1;36m  ████   \033[0;37mA simple AUR helper\n");
	printf("\033[1;36m  █	   \033[0;37mCopyright-GPL '21\n");
	printf("\033[1;36m  █	   \033[1;33m         noStress\n\n");
	exit(0);
}

int
main (int argc, char *argv[])
{
	int opt,   pexac;
	int pvers, phelp;
	int plook;

	plook   = 0;
	pexac   = 0;
	phelp   = 0;
	pvers   = 0;
	struct option longopts[] = {
		{ "help",     no_argument, NULL, 'h' },
		{ "exact",    no_argument, NULL, 'e' },
		{ "search",   no_argument, NULL, 's' },
		{ "version",  no_argument, NULL, 'V' },
		{ 0, 0, 0, 0 }
	};
	while ((opt = getopt_long(argc, argv, "Vseh", longopts, NULL)) != -1) {
		switch (opt) {
		case 's':
			if (plook || pexac) {
				errorAndDie(1);
			} else {
				plook++;
			}
			break;
		case 'e':
			if (pexac || plook) {
				errorAndDie(1);
			} else {
				pexac++;
			}
			break;
		case 'h':
			usage();
			break;
		case 'V':
			version();
			break;
		default: /* ? */
			usage(0);
		}
	}

	if (plook || pexac) {
		if (!argv[optind])
			errorAndDie(3);
		else {
			while (optind < argc) {
				parse(plook, pexac, argv[optind]);
				optind++;
			}
		}
	} else
		errorAndDie(2);

	return 0;
}
